#coding:utf-8
'''
Created on 2017年10月19日

@author: lanjinmin
'''
import emoji
import urllib

from flask import request,redirect, session

from example.worker import app
from example.utils.authclient import authclient
from example.utils.data_config import IDENTITY_WECHAT, IDENTITY_BAIDU, \
                    IDENTITY_QQ_MOBILE, IDENTITY_WEIBO
from example.utils.tool_func import  setSecretCookie,\
                            delSecretCookie, getSecretCookie, produce_access_token
from example.utils.config import USER_COOKIE_KEY
from example.utils.decorator import login_required
from example.utils.baiduclient import bdclient
from example.utils.errors import *
from example.utils.qqauthclient import qqclient
from example.utils.sinaclient import sinaclient

@app.route('/auth/login',methods=["GET"])
def auth_login():
    """授权登录
    """
    ref = request.referrer
    login_url = "/auth/login_redirect?redirect_to=%s"%urllib.quote(str(ref), safe="")
    return redirect(login_url)
    
@app.route('/auth/login_redirect',methods=["GET"])
@login_required
def login_redirect():
    """登录跳转
    """
    redirect_to = request.args.get("redirect_to")
    print 'redirect_to',redirect_to
    if not redirect_to:
        redirect_to = "/games/home"
    return redirect(redirect_to)
    
@app.route('/auth/wechat_auth',methods=["GET"])
def wechat_auth():
    """微信授权
    """
    appid = request.args.get("appid")
    bkurl=request.args.get("bkurl")#获取回调页面
    openid=request.args.get("openid")
    timestamp = request.args.get("timestamp","0")
    sign = request.args.get("sign")
    bkurl = urllib.unquote(bkurl)
    props = {"appid":appid,"openid":openid,"timestamp":int(timestamp),"sign":sign}
    if not authclient.check_auth_data(props):
        return "auht error"
#     user_info = authclient.get_user_info(openid).get("user_info")
#     headimgurl = user_info.get("headimgurl","")
#     unionid=user_info.get("unionid","")
#     try:
#         auth_info = AuthInfo.objects.get(identifier=openid,identity_type=IDENTITY_WECHAT)
#     except:
#         unionid=user_info.get("unionid","")
#         if unionid:
#             try:
#                 other_auth_info = AuthInfo.objects.get(unionid=unionid)
#             except:
#                 other_auth_info = None
#         else:
#             other_auth_info = None
#         if not other_auth_info:
#             user = UserInfo(nickname=user_info.get("nickname",""),
#                             avatar=headimgurl,sex=user_info.get("sex",1),city=user_info.get("city",""),
#                             country=user_info.get("country",""),province=user_info.get("province",""))
#             user.save()
#         else:
#             user = other_auth_info.user
#         auth_info = AuthInfo(user=user,identifier=openid,identity_type=IDENTITY_WECHAT)
#         auth_info.save()
#     user = auth_info.user
#     if user.avatar!=headimgurl:#更新用户头像
#         user.avatar = headimgurl
#         user.save()
    user = None
    access_token = produce_access_token(user.id)
    response = redirect(bkurl)
    setSecretCookie(response, USER_COOKIE_KEY, access_token,18000)
    return response

@app.route('/auth/baidu_auth', methods=['GET'])
def baidu_auth():
    """"百度授权
    """
    code = request.args.get('code','')
    bkurl = request.args.get('bkurl','')
    redirect_url = session['redirect_url_bak']#'http://game.meet.henkuai.com/auth/baidu_auth?bkurl=http://game.meet.henkuai.com/auth/login_redirect?redirect_to=http%3A%2F%2Fgame.meet.henkuai.com%2Fgames%2Fuser_center'
    token = bdclient.get_token(code,redirect_url)
    user_info = bdclient.get_user_info(token)
    head_img = '%s%s'%('http://tb.himg.baidu.com/sys/portraitn/item/',user_info['portrait'])
    nickname = user_info.get("username")
    user_identifier = user_info['userid']
    print user_identifier
    sex_info = 1
    if user_info['sex'] == '0':
        sex_info = 2
#     auth_info = None
#     try:
#         auth_info = AuthInfo.objects.get(identifier=user_info['userid'],identity_type=IDENTITY_BAIDU)
#     except:
#         auth_info = AuthInfo(identifier=user_info['userid'],identity_type=IDENTITY_BAIDU)
#         auth_info.save()
#         return render_template('games_extend.html', **locals())
#     if auth_info.user == None:
#         return render_template('games_extend.html', **locals())
#     user = auth_info.user
#     if user.avatar!=head_img:#更新用户头像
#         user.avatar = head_img
#         user.save()
    user = None
    access_token = produce_access_token(user.id)
    response = redirect(bkurl)
    setSecretCookie(response, USER_COOKIE_KEY, access_token,18000)
    return response


@app.route('/auth/qq_auth', methods=['GET'])
def qq_auth():
    """QQ登陆授权
    """
    code = request.args.get('code','')
    bkurl = request.args.get('bkurl','')
    print 'bkurl',bkurl
    redirect_url = session['redirect_url_bak']
    token = qqclient.get_token(code,redirect_url)
    user_info = qqclient.get_qquser_openid(token)
    user_detail = qqclient.get_userinfo(token, user_info['openid'])
    print user_detail
    sex_info = 2
    if user_detail['gender'] == '男':
        sex_info = 1
#     auth_info = None
#     try:
#         auth_info = AuthInfo.objects.get(identifier=user_info['openid'],identity_type=IDENTITY_QQ_MOBILE)
#     except:
#         user = UserInfo(nickname=user_detail.get('nickname'),
#                         avatar=user_detail.get('figureurl_qq_2'),
#                         sex=sex_info,
#                         city=user_detail.get('city'),
#                         country='0',
#                         province=user_detail.get('province'))
#         user.save()
# #             user = other_auth_info.user
#         auth_info = AuthInfo(user=user,identifier=user_info['openid'],identity_type=IDENTITY_QQ_MOBILE)
#         auth_info.save()
#     user = auth_info.user
#     if user.avatar!=user_detail.get('figureurl_qq_2'):#更新用户头像
#         user.avatar = user_detail.get('figureurl_qq_2')
#         user.save()
    user = None
    access_token = produce_access_token(user.id)
    response = redirect(bkurl)
    setSecretCookie(response, USER_COOKIE_KEY, access_token,18000)
    return response

@app.route('/auth/sina_auth', methods=['GET'])
def sina_auth():
    """新浪微博授权
    """
    code = request.args.get('code')
    redirect_url = session['redirect_url_bak']
    print redirect_url
    return_jump_url = session['return_jump_url']
    print 'return_jump_url',return_jump_url
    tokeninfo = sinaclient.get_token(code,redirect_url)
    userinfo = sinaclient.get_user_info(tokeninfo['access_token'],tokeninfo['uid'])
    sex_info = 2
    if userinfo['gender'] == 'm':
        sex_info = 1
#     auth_info = None
#     try:
#         auth_info = AuthInfo.objects.get(identifier=tokeninfo['uid'],identity_type=IDENTITY_WEIBO)
#     except:
#         user = UserInfo(nickname=userinfo.get('name'),
#                         avatar=userinfo.get('profile_image_url'),
#                         sex=sex_info,
#                         city=userinfo.get('location'),
#                         country=userinfo.get('location'),
#                         province=userinfo.get('province'))
#         user.save()
# #             user = other_auth_info.user
#         auth_info = AuthInfo(user=user,identifier=tokeninfo['uid'],identity_type=IDENTITY_WEIBO)
#         auth_info.save()
#     user = auth_info.user
#     if user.avatar!=userinfo.get('profile_image_url'):#更新用户头像
#         user.avatar = userinfo.get('profile_image_url')
#         user.save()
    user = None
    access_token = produce_access_token(user.id)
    response = redirect(return_jump_url)
    setSecretCookie(response, USER_COOKIE_KEY, access_token,18000)
    return response
